package com.iaiai.cobra.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iaiai.cobra.common.constant.YesOrNo;
import com.iaiai.cobra.repository.bean.RoleMenu;
import com.iaiai.cobra.repository.mapper.RoleMenuMapper;
import com.iaiai.cobra.system.service.RoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with RoleMenuServiceImpl.
 * Package: com.iaiai.cobra.system.service.impl
 * Author: iaiai
 * Create Time: 2024/7/16 21:25
 * QQ: 176291935
 * Email: 176291935@qq.com
 * Description:
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    //查询配置的菜单
    public List<RoleMenu> queryMenus(Long roleId){
        return getBaseMapper().queryMenus(roleId);
    }

    //保存菜单
    @Transactional(rollbackFor = Exception.class)
    public void editMenu(Long roleId,List<Long> menuIds){
        //先查出之前配置的
        List<RoleMenu> roleMenus = queryMenus(roleId);
        if(roleMenus==null)roleMenus = new ArrayList<>();
        List<Long> originMenuIds = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());

        //找出多余的元素
        List<Long> addMenuIds = menuIds.stream()
                .filter(element -> !originMenuIds.contains(element))
                .collect(Collectors.toList());

        // 找出被删除的元素
        List<Long> delMenuIds = originMenuIds.stream()
                .filter(element -> !menuIds.contains(element))
                .collect(Collectors.toList());

        if(addMenuIds!=null && addMenuIds.size()>0){
            for (Long addMenuId : addMenuIds) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(addMenuId);
                roleMenu.setCreateTime(new Date());
                roleMenu.setModifyTime(roleMenu.getCreateTime());
                roleMenu.setDel(YesOrNo.NO.getValue());
                getBaseMapper().insert(roleMenu);
            }
        }

        if(delMenuIds!=null && delMenuIds.size()>0){
            for (Long delMenuId : delMenuIds) {
                getBaseMapper().delRoleMenu(roleId,delMenuId);
            }
        }
    }

    //删除菜单
    public void delMenu(Long menuId){
        getBaseMapper().delMenu(menuId);
    }

    //删除角色
    public void delRole(Long roleId){
        getBaseMapper().delRole(roleId);
    }

}
